﻿using System;

using NJ.Common.Configs;
using NJ.Common.Extension;
using NJ.Common.Ioc;
using NJ.Common.Tools.Encrypt;
using NJ.Common.Web;
using NJ.Dto.User;
using NJ.Service.User;

namespace NJ.Web.Models
{
    public class CurUser
    {
        private static readonly string cookieName = Configs.GetValue("CookieName");
        private static readonly string sessionName = Configs.GetValue("SessionName");
        private static readonly string sysSecret = Configs.GetValue("SysSecret");
        private static IUserService userService = AutoFacConfig.Resolve<IUserService>();

        /// <summary>
        /// 设置登录用户
        /// </summary>
        /// <param name="userDto"></param>
        public static void Set(UserDto userDto)
        {
            if (userDto != null)
            {
                string secret = TripleDES.Encrypt(userDto.Id.ToString(), sysSecret);
                Storage.SetCookie(cookieName, secret);
                Storage.SetSession(sessionName, userDto);
            }
            else
            {
                throw new Exception("user Is Null");
            }
        }

        public static bool IsLogin()
        {
            string secret = Storage.GetCookie(cookieName);

            return !secret.IsNullOrWhiteSpace() && !TripleDES.Decrypt(secret, sysSecret).IsNullOrWhiteSpace();
        }

        /// <summary>
        /// 获取登录用户
        /// </summary>
        /// <returns></returns>
        public static UserDto GetAsync()
        {
            var secret = Storage.GetCookie(cookieName);
            var UserId = TripleDES.Decrypt(secret, sysSecret).To<int>();
            UserDto userDto = Storage.GetSession<UserDto>(sessionName);
            if (userDto == null)
            {
                userDto = userService.GetUser(UserId);
                Storage.SetSession(sessionName, userDto);

            }
            return userDto;
        }
        public static UserDto Model => GetAsync();
        /// <summary>
        /// 移除登录用户
        /// </summary>
        public static void Clear()
        {
            Storage.RemoveSession(sessionName);
            Storage.RemoveCookie(cookieName);
        }
        /// <summary>
        /// 移除登陆session
        /// </summary>
        public static void ClearSession()
        {
            Storage.RemoveSession(sessionName);
        }
        /// <summary>
        /// 移除登陆cookie
        /// </summary>
        public static void ClearCookie()
        {
            Storage.RemoveCookie(cookieName);
        }
    }
}